<?php

namespace Modules\Production\Repository;

use Illuminate\Support\Facades\DB;
use Mockery\Exception;
use Modules\Production\Models\ProductionOrderStockUser;

class ProductionOrderStockUserRepository
{

    /**
     * 添加生产工单指派人员
     * @param $uid 操作人员id
     * @param $orderId 生产工单id
     * @param $userId 指派人员id
     * @return mixed
     */
    public function save($uid,$orderId,$userId){

        $stockUsr = [];
        foreach ($orderId as $val){
            foreach ($userId as $userVal){
                $stockUsr[] = [
                    'production_order_id' => $val,
                    'user_id' => $userVal['id'],
                    'user_name' => $userVal['name'],
                    'creator_id' => $uid,
                    'created_at' => time(),
                ];
            }
        }

        try {
            DB::beginTransaction();

            ProductionOrderRepository::setOrderStockUser($orderId);
            ProductionOrderStockUser::whereIn('production_order_id',$orderId)->delete();
            ProductionOrderStockUser::insert($stockUsr);

            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }

    }


    static public function findByProductionId($productionId){
        return ProductionOrderStockUser::where('production_order_id',$productionId)->get();
    }

}
